﻿/*
 * Создан: Оникийчук Антон Игоревич
 * Компания: ООО "ИМСАТ"
 * Дата создания: 21.01.2009
 * Время создания: 10:24
 * Emal разработчика: onikiychuka@gmail.com
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml;

namespace IMSAT.OFTD.DOM
{
    /// <summary>
    /// Страница
    /// </summary>
    public class Page : Node
    {
        private readonly MemoryStream _svgStream = new MemoryStream();

        private string _name = "";

        private ElementCollection _pageElements;

        public LinkCollection PageLinks
        {
            get { return _pageLinks; }
        }
        public SectionCollection PageSections { get; private set; }


        private LinkCollection _pageLinks;
        private XmlWriter _svgWriter;

        public Page()
        {
            _pageLinks = new LinkCollection(ChildNodes);
            _pageElements = new ElementCollection(ChildNodes);
            PageSections = new SectionCollection(ChildNodes);
        }

        public string Name
        {
            get { return _name; }
        }

        public double Width { get; set; }

        public double Height { get; set; }

        protected void AppendSvg(XmlReader xmlsvg)
        {
            if (_svgWriter == null)
            {
                _svgWriter = XmlWriter.Create(_svgStream);
                doc_finished = false;
            }
            _svgWriter.WriteNode(xmlsvg, true);
        }

        bool doc_finished = false;

        ///<summary>
        /// Получить поток сожержащий svg изображение данной страницы
        /// </summary>
        /// <returns>Поток содержащий svg</returns>	
        public Stream GetSvgStream()
        {
            if (!doc_finished)
            {
                _svgWriter.WriteEndDocument();
                _svgWriter.Flush();
                doc_finished = true;
            }
            _svgStream.Position = 0;
            return new BufferedStream(_svgStream, Convert.ToInt32(_svgStream.Length));
        }
        public IEnumerable<Element> FindElements()
        {
            return Find(
                delegate(Node nd)
                {
                    if (nd is Element)
                        return true;
                    return false;
                }, false).Cast<Element>();
        }

        /// <summary>
        /// Получить строку содержащую svg этой страницы.
        /// </summary>
        /// <returns>строка содержащая svg</returns>
        public string GetSvgString()
        {
            if (!doc_finished)
            {
                _svgWriter.WriteEndDocument();
                _svgWriter.Flush();
                doc_finished = true;
            }
            _svgStream.Position = 0;
            var sr = new StreamReader(_svgStream);
            return sr.ReadToEnd();
        }

        #region Nested type: Reader

        public class Reader : NodeXmlReader
        {
            protected override bool CheckReader(XmlReader rd, bool _prevRes, Node parentNode)
            {
                if (_prevRes)
                {
                    if (rd.LocalName == "Лист")
                        return true;
                    return false;
                }
                return base.CheckReader(rd, _prevRes, parentNode);
            }

            protected override Node InitNode(XmlReader reader, Node initedNode)
            {
                if (initedNode == null)
                    initedNode = new Page();
                var p = (Page) initedNode;

                int cnt = reader.AttributeCount;
                for (int i = 0; i < cnt; i++)
                {
                    reader.MoveToAttribute(i);
                    if (reader.LocalName == "Ширина")
                    {
                        double data = Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture);
                        p.Width = data;
                    }
                    else if (reader.LocalName == "Высота")
                    {
                        double data = Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture);
                        p.Height = data;
                    }
                    else
                    {
                        var prop = new Property(reader.LocalName, new XmlNamespace(reader.NamespaceURI, reader.Prefix));
                        prop.Value = reader.Value;
                        p.AppendChild(prop);
                    }
                    reader.MoveToElement();
                }
                return base.InitNode(reader, initedNode);
            }

            protected override Node InitObjectAfterBuild(Node result)
            {
            	DateTime startTime = DateTime.Now;
                NodeCollection<Node> fr = result.Find(src=>src is SvgNode);
                var p = (Page) result;
                if (p._svgWriter == null)
                {
                    p._svgWriter = XmlWriter.Create(p._svgStream);
                }
                p._svgWriter.WriteStartDocument();

                var sn = (SvgNode) (fr.First());
                sn.Data.Position = 0;
                XmlReader rd = XmlReader.Create(sn.Data);
                while (rd.Read())
                {
                    if (rd.NodeType == XmlNodeType.Element) break;
                }
                p._svgWriter.WriteNode(rd, false);
                
                result.Find(n => n is Section || n is Link).Select(n => result.AppendChild(n)).ToArray();



                var specialHolders = result.Find((n)=>!n.HasChild ? false :
                                                        n.ChildNodes[0] is Link ? true :
                                                        n.ChildNodes[0] is Section ? true :
                                                        false);
                using (var nce = result.ChildNodes.BeginEdit())
                {
                    foreach (var holder in specialHolders)
                    {
                        result.ChildNodes.Remove(holder);
                    }
                    foreach (var l in p._pageLinks)
                    {
                        l.SetelemsByID(p);
                    }
                    foreach (var section in p.PageSections)
                    {
                        foreach (var elmLnk in section.Elements)
                        {
                            elmLnk.SetelemsByID(p);
                        }
                    }
                }


                TimeSpan res = DateTime.Now - startTime;
                return base.InitObjectAfterBuild(result);
            }
        }

        #endregion
    }
}